from copy import copy

class EventServer:
    def __init__(self):
        self.subscriptions = {}
        self.providers = {}
        
    def addProvider(self, prefix, f):
        self.providers.setdefault(prefix,set()).add(f)
        
    def subscribe(self, cmd, f):
        if cmd != 'update':
            from networkServer import networkServer
            networkServer.subscribe(cmd)
        self.localSubscribe(cmd,f)
        
    def localSubscribe(self, cmd, f):
        self.subscriptions.setdefault(cmd,set()).add(f)
        if '_' in cmd:
            prefix, providerCmd = cmd.split('_')
            if prefix in self.providers:
                for f in self.providers[prefix]:
                    f(providerCmd)
                    
    def unsubscribe(self, cmd, f):
        #need to count subscriptions on server in order to be able to do this
        #sub - sub - unsub - first sub is disconnected!
        #if cmd != 'update':
            #from networkServer import networkServer
            #networkServer.unsubscribe(cmd)
        self.localUnsubscribe(cmd,f)
        
    def localUnsubscribe(self, cmd, f):
        self.subscriptions[cmd].remove(f)
        
    def publish(self, cmd, **args):
        self.localPublish(cmd,**args)
        from networkServer import networkServer
        networkServer.publish(cmd,args)
        
    def localPublish(self, cmd, **args):
        if cmd in self.subscriptions:
            for f in copy(self.subscriptions[cmd]):
                f(args)

eventServer = EventServer()
